package com.DosonLeung.homeschoolcommunication.Controllers;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.DosonLeung.homeschoolcommunication.Constant.SystemConstant;
import com.DosonLeung.homeschoolcommunication.Constant.UserConstant;
import com.DosonLeung.homeschoolcommunication.Models.MainModel;
import com.DosonLeung.homeschoolcommunication.Models.SystemModel;
import com.DosonLeung.homeschoolcommunication.Modules.SystemAlbumModule.SystemAlbumActivity;
import com.DosonLeung.homeschoolcommunication.R;
import com.DosonLeung.homeschoolcommunication.Services.MainBinder;
import com.DosonLeung.homeschoolcommunication.Utils.ImageUtil;
import com.DosonLeung.homeschoolcommunication.Utils.NetWorkUtil;
import com.DosonLeung.homeschoolcommunication.Utils.UpdataUtil;
import java.io.File;


public class MainActivity extends Activity {

    MainActivity self = this;
    MainModel mainModel;
    MainBinder serviceBinder;
    Handler serviceHandler;
    Intent serviceIntent;
    ServiceConnection conn;
    ProgressDialog pd;

    //main_contacts 联系人消息页面及其组件
    RelativeLayout mainContact;
    ListView mainClassList;
    ListView mainContactList;
    Button pressMainClass;
    Button pressMainContact;

    //main_chats 聊天页面及其组件
    RelativeLayout mainChats;
    FrameLayout groupChat;
    ListView mainChatList;

    //设置页面及其组件
    RelativeLayout mainSetting;
    FrameLayout mainSettingTable;
    ImageView settingMyIcon;
    TextView settingName;
    TextView settingSalutation;
    TextView settingGuardian;
    TextView settingContact;
    TextView settingChildName;
    TextView settingSchool;
    TextView settingClass;
    CheckBox settingNotify;

    //账号设置页面
    Button logOut;
    Button clearHistory;
    CheckBox autoLogin;

    //设置footer布局
    TextView footerDot;
    FrameLayout footer;
    Button footerContact;
    Button footerChats;
    Button footerSetting;
    ImageView imgContact;
    ImageView imgChats;
    ImageView imgSetting;

    String url = "";

    /*
    * 0x100 service获取到了MainActivity的Handler
    * 0x200 获取同一班级其他成员信息成功
    * 0x201 被Service要求更新视图
    * 0x202 接受到一幅新的人物icon
    * 0x300 开启菊花（开始加载联系人信息）
    * 0x404 网络超时
    * 0x444 账号在其他设备登录需要退出
    * 0x500 运行mianModel的getPersonDataByNetWork()出现错误，强制关闭菊花
    * */
    final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x100:
                    mainModel.init();//初始化mainModel
                    Log.e("MainActivity", "service get mainHandler successfully!");
                    break;
                case 0x200:
                    //stopReflashDialog();
                    if (UserConstant.USER_CHARACTER.equals("")) {
                        Log.e("MainActivity", "you haven't choose a role!");
                    } else {
                        //网络其他成员信息成功，所以不需要再从网络加载,告之Service
                        mainModel.notifyAllViews();
                        serviceHandler.sendEmptyMessage(0x502);//通知Service,MainActivity可用
                        serviceHandler.sendEmptyMessage(0x102);//启动Socket
                    }
                    break;
                case 0x201://条件更新, 刷新时间不小于1秒
                    mainModel.refreshAllDataList(false);
                    mainModel.notifyAllViews();
                    refreshDot();
                    break;
                case 0x202:
                    mainModel.asyncNotifyView();
                    break;
                case SystemConstant.UPLOAD_IMAGE_SUCCESS:
                    stopReflashDialog();
                    Toast.makeText(self,"上传成功！",Toast.LENGTH_SHORT).show();
                    if(!url.equals(""))
                        UserConstant.USER_AVATAR_PATH = url;
                    break;
                case 0x404:
                    stopReflashDialog();
                    Toast.makeText(self, "网络超时!无法加载联系人信息", Toast.LENGTH_SHORT).show();
                    break;
                case SystemConstant.UPLOAD_IMAGE_FAIL:
                    stopReflashDialog();
                    Toast.makeText(self,"上传失败！",Toast.LENGTH_SHORT).show();
                    url = "";
                case SystemConstant.LOG_STRANGE:
                    Toast.makeText(self,"你的账号在其它设备登录，请重新登录",Toast.LENGTH_LONG).show();
                    serviceHandler.sendEmptyMessage(0x444);//通知service停止服务
                    unbindService(conn);
                    SystemModel.logOutButRememberMe(self);
                    break;
                case 0x300:
                    showReflashDialog("加载联系人信息中");
                    break;
                case 0x500:
                    stopReflashDialog();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        initWidgets();
        initTabs();
        initAccountSetting();
        mainModel = new MainModel(self, UserConstant.USER_CHARACTER, mHandler);
        mainModel.setpChatsListView(this.mainChatList);
        mainModel.setpContactsListView(this.mainContactList);
        mainModel.settChatsListView(this.mainChatList);
        mainModel.settContactsListView(this.mainContactList);
        mainModel.settClassListView(this.mainClassList);
        startSevice();
    }

    private void startSevice() {
        serviceIntent = new Intent();
        serviceIntent.setAction("com.DosonLeung.homeschoolcommunication.Services.BIND_SERVICE");
        conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                serviceBinder = (MainBinder) service;
                serviceHandler = serviceBinder.getServiceHandler();
                serviceBinder.setMainHandler(mHandler);
                try {
                    //startService,发送0x100通知service表示收到了
                    serviceHandler.sendEmptyMessage(0x100);
                    mainModel.setServiceHandler(serviceHandler);
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }

            //与Service断开连接只有退出程序或者注销
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e("MainActivity:", "Disconnected with MainService!");
            }
        };
        boolean status = bindService(serviceIntent, conn, Service.BIND_AUTO_CREATE);
        if (!status) {
            Toast.makeText(self, "bindService failed!", Toast.LENGTH_SHORT).show();
        }
    }

    private void initWidgets() {
        //main_contacts 联系人消息页面及其组件
        mainContact = (RelativeLayout) findViewById(R.id.main_contacts);
        mainContactList = (ListView) findViewById(R.id.main_contact_list);
        mainClassList = (ListView) findViewById(R.id.main_class_list);
        pressMainClass = (Button) findViewById(R.id.press_main_class);
        pressMainContact = (Button) findViewById(R.id.press_contact_list);

        //main_chats 聊天页面及其组件
        mainChats = (RelativeLayout) findViewById(R.id.main_chats);
        groupChat = (FrameLayout) findViewById(R.id.add_chat);
        mainChatList = (ListView) findViewById(R.id.main_chats_list);
        groupChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pressGroupChat();
            }
        });

        //设置页面及其组件
        mainSetting = (RelativeLayout) findViewById(R.id.main_setting);
        mainSettingTable = (FrameLayout) findViewById(R.id.main_setting_table);
        settingMyIcon = (ImageView) findViewById(R.id.main_setting_myicon);
        settingName = (TextView) findViewById(R.id.main_setting_name);
        settingSalutation = (TextView) findViewById(R.id.main_setting_salutation);
        settingGuardian = (TextView) findViewById(R.id.main_setting_guardian);
        settingContact = (TextView) findViewById(R.id.main_setting_contact);
        settingChildName = (TextView) findViewById(R.id.main_setting_childname);
        settingSchool = (TextView) findViewById(R.id.main_setting_school);
        settingClass = (TextView) findViewById(R.id.main_setting_class);
        settingNotify = (CheckBox) findViewById(R.id.main_setting_notify);

        //设置footer布局
        footerDot = (TextView) findViewById(R.id.main_footer_sum);
        footer = (FrameLayout) findViewById(R.id.main_footer);
        footerContact = (Button) findViewById(R.id.main_footer_contact);
        footerChats = (Button) findViewById(R.id.main_footer_chats);
        footerSetting = (Button) findViewById(R.id.main_footer_setting);
        imgChats = (ImageView) findViewById(R.id.img_chats);
        imgContact = (ImageView) findViewById(R.id.img_contact);
        imgSetting = (ImageView) findViewById(R.id.img_setting);

        //账号设置页面
        logOut = (Button) findViewById(R.id.log_out);
        clearHistory = (Button) findViewById(R.id.clear_history);
        autoLogin = (CheckBox) findViewById(R.id.login_automatically);

    }

    private void initTabs() {
        mainChats.setVisibility(View.GONE);
        footer.setVisibility(View.VISIBLE);
        footerDot.setVisibility(View.GONE);
        mainContact.setVisibility(View.VISIBLE);
        mainSetting.setVisibility(View.GONE);
        imgChats.setVisibility(View.GONE);
        imgContact.setVisibility(View.VISIBLE);
        imgSetting.setVisibility(View.GONE);
        footerChats.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mainChats.setVisibility(View.VISIBLE);
                mainContact.setVisibility(View.GONE);
                mainSetting.setVisibility(View.GONE);
                imgChats.setVisibility(View.VISIBLE);
                imgContact.setVisibility(View.GONE);
                imgSetting.setVisibility(View.GONE);
            }
        });
        footerContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mainChats.setVisibility(View.GONE);
                mainContact.setVisibility(View.VISIBLE);
                mainSetting.setVisibility(View.GONE);
                imgChats.setVisibility(View.GONE);
                imgContact.setVisibility(View.VISIBLE);
                imgSetting.setVisibility(View.GONE);
            }
        });
        footerSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mainChats.setVisibility(View.GONE);
                mainContact.setVisibility(View.GONE);
                mainSetting.setVisibility(View.VISIBLE);
                imgChats.setVisibility(View.GONE);
                imgContact.setVisibility(View.GONE);
                imgSetting.setVisibility(View.VISIBLE);
            }
        });
    }

    private void initAccountSetting() {
        String grade = UserConstant.USER_GRADE;
        grade = grade.replace("[", "");
        grade = grade.replace("]", "");
        grade = grade.replace("\"", "");
        if (UserConstant.USER_CHARACTER.equals("patriarch")) {
            mainClassList.setVisibility(View.GONE);
            pressMainClass.setVisibility(View.GONE);
            pressMainContact.setVisibility(View.VISIBLE);
            ImageUtil.getMyIcon(settingMyIcon);
            settingName.setText(UserConstant.USER_NAME);
            settingSalutation.setText(UserConstant.USER_SEX);
            settingGuardian.setText(UserConstant.USER_GRADIAN);
            settingContact.setText(UserConstant.USER_CONTACT);
            settingChildName.setText(UserConstant.USER_CHILD_NAME);
            settingSchool.setText(UserConstant.USER_SCHOOL);

            settingClass.setText(grade);
        } else {
            mainClassList.setVisibility(View.VISIBLE);
            ImageUtil.getMyIcon(settingMyIcon);
            settingName.setText(UserConstant.USER_NAME);
            settingSalutation.setText(UserConstant.USER_SEX);
            settingGuardian.setText(UserConstant.USER_GRADIAN);
            settingContact.setText(UserConstant.USER_CONTACT);
            settingChildName.setText(UserConstant.USER_CHILD_NAME);
            settingSchool.setText(UserConstant.USER_SCHOOL);
            settingClass.setText(grade);
        }
        settingMyIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPhotoFromAlbum(self);
            }
        });
        logOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        clearHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressClearHistory(v);
            }
        });
        autoLogin.setChecked(SystemModel.getLoginStatus(self));
        autoLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                pressAutoLogin(isChecked);
            }
        });
        settingNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                pressAutoCheck(isChecked);
            }
        });
        settingNotify.setChecked(true);//默认接收新消息

    }

    //提醒service进入groupchat状态
    private void pressGroupChat(){
        Bundle data = new Bundle();
        data.putString("targetId","groupchat");//群发消息
        Message msg = new Message();
        msg.setData(data);
        msg.what = 0x201;//进入MainActivity勿扰模式
        serviceHandler.sendMessage(msg);
        Intent intent = new Intent(self,GroupChatActivity.class);
        self.startActivityForResult(intent, SystemConstant.CHAT_CODE);
    }

    public void onBackPressed() {
        new AlertDialog.Builder(MainActivity.this).setTitle("是否退出登录")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 点击“确认”后的操作
                        serviceHandler.sendEmptyMessage(0x444);//通知service停止服务
                        unbindService(conn);
                        SystemModel.logOut(self);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 点击“返回”后的操作,这里不设置没有任何操作
                    }
                }).show();
    }

    private void pressClearHistory(View v) {
        new AlertDialog.Builder(MainActivity.this).setTitle("清除数据后需要重新登陆，是否继续？")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 点击“确认”后的操作
                        serviceHandler.sendEmptyMessage(0x444);//通知service停止服务
                        unbindService(conn);
                        SystemModel.clearHistory(self);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 点击“返回”后的操作,这里不设置没有任何操作
                    }
                }).show();
    }

    //調用SystemAlbumModule,從相冊獲取圖片
    public boolean getPhotoFromAlbum(Activity app){
        try {
            Intent intent = new Intent(app, SystemAlbumActivity.class);
            app.startActivityForResult(intent, SystemConstant.GET_PHOTO_FROM_ALBUM);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void pressAutoLogin(boolean isChecked) {
        SystemModel.autoLogin(self,isChecked);
    }

    private void pressAutoCheck(boolean isChecked) {
        SystemConstant.autonotify = isChecked;
    }

    /*
    * 注册成功后,自动登录
    * **/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == SystemConstant.CHAT_CODE) {
            switch (requestCode) {
                case SystemConstant.CHAT_CODE:
                    Bundle data = intent.getExtras();
                    if (data.getBoolean("chat")) {
                        serviceHandler.sendEmptyMessage(0x400);
                        refreshDot();
                        //serviceHandler.sendEmptyMessage(0x502);
                    }
                    break;
                default:
                    break;
            }
        }else if (resultCode == RESULT_OK) {
            String url;
            switch (requestCode) {
                case SystemConstant.GET_PHOTO_FROM_ALBUM:
                    url = intent.getStringExtra("album");
                    File file = new File(url);
                    settingMyIcon.setImageBitmap(ImageUtil.getBitmapByFilePath(url));
                    if(file.exists())
                        if(NetWorkUtil.getAvailableNetWorkInfo(self)) {
                            UpdataUtil.uploadFile(file, file.getName(), true, mHandler);
                            showReflashDialog("上传新头像中......");
                            this.url = url;
                        }
                        else
                            Toast.makeText(self,"上传失败，请检查你的网络状态",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    }

    private void refreshDot() {
        String sum = SystemConstant.getSum();
        if (sum.equals("0")) {
            footerDot.setVisibility(View.GONE);
        } else {
            footerDot.setVisibility(View.VISIBLE);
            if (Integer.parseInt(sum) < 100) {
                footerDot.setText(sum);
            } else
                footerDot.setText("99+");
        }
    }

    /**
     * 显示刷新的时候的等待进度条
     */
    private void showReflashDialog(String msg) {
        this.pd = new ProgressDialog(this);
        this.pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        this.pd.setCancelable(false);
        this.pd.setMessage(msg);
        this.pd.setMax(20);
        this.pd.show();
    }

    /**
     * 结束刷新的时候的等待进度条
     */
    private void stopReflashDialog() {
        if (this.pd != null) {
            pd.dismiss();
        }
    }

    //当MainActivity处于后台或者不可见时，向Service发送信号
    @Override
    public void onPause() {
        serviceHandler.sendEmptyMessage(0x500);
        super.onPause();
    }

    @Override
    public void onRestart() {
        serviceHandler.sendEmptyMessage(0x502);
        super.onRestart();
        Log.e("MainActivity", "Back to the mainactivity!");
        mainModel.refreshAllDataList(false);
        mainModel.notifyAllViews();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if(mainModel!=null)
            mainModel.closeMemberDB();
        super.onDestroy();
    }

}
